package com.gxa.pingan.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author YXQ
 * @date 2021/11/3 8:26
 */
public class ResponseUtil {
    public static void write(HttpServletResponse response, Map<String ,Object> map){
        // 设置响应类型的字符集
        response.setCharacterEncoding("UTF-8");
        // 设置请求头
        response.setHeader("content-Type", "text/html;charset=utf-8");
        // 转化JSON的jackson
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 通过字符输出流writer写给前端
            PrintWriter writer = response.getWriter();
            // 将map对象转换成json字符串
            // writer.print(JSON.toJSONString(map));
            writer.print(objectMapper.writeValueAsString(map));
            // 刷新流
            writer.flush();
            // 关闭流
            writer.close();
        } catch (IOException e) {
            // 打印异常--控制台
            e.printStackTrace();
        }
    }
}
